//
//  ICLoginViewController.m
//  ICome
//
//  Created by ENN on 16/2/18.
//  Copyright © 2016年 XianZhuangGuo. All rights reserved.
//  登录控制器

#import "ICLoginViewController.h"
#import "ICDatabaseManager.h"
#import "MJExtension.h"
#import "ICLoginTextField.h"
#import "ICNetworkHelper.h"
#import "ICLoginNetworkManager.h"
#import "IComMediator.h"
#import "ICDefaultConfigManager.h"
#import "ICNavigationController.h"
#import "ICHeaderFile.h"

static const CGFloat LoginGap = 28.;
static const CGFloat LoginIconViewHeight = 48.;
static const CGFloat LoginIconViewTop = 80.;
static const CGFloat LoginFieldHeight = 55.;

@interface ICLoginViewController ()

@property (nonatomic, strong) UIView *iconView;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, weak) UIButton *loginBtn;
@property (nonatomic, weak) ICLoginTextField *accField;
@property (nonatomic, weak) ICLoginTextField *passField;

@end

@implementation ICLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUNDCOLOR;
    [self setHeaderView];
    [self setLoginView];
}


- (void)setHeaderView
{
    _iconView = [[UIView alloc] initWithFrame:CGRectMake(0, LoginIconViewTop, kScreenWidth, LoginIconViewHeight)];
    [self.view addSubview:_iconView];
    
    UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(LoginGap, 0, LoginIconViewHeight, LoginIconViewHeight)];
    logoImageView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_login_logo"];


    [_iconView addSubview:logoImageView];
    
    UILabel *loginLabel = [[UILabel alloc] initWithFrame:CGRectMake(logoImageView.right+10, 0, 200., 30+1.)];
    loginLabel.text = @"登录iCome";
    loginLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    loginLabel.font = [UIFont systemFontOfSize:30];
    loginLabel.textAlignment = NSTextAlignmentLeft;
    [_iconView addSubview:loginLabel];
    
    UILabel *desLabel = [[UILabel alloc] initWithFrame:CGRectMake(loginLabel.left, loginLabel.bottom+2, 200., 14+1.)];
    desLabel.text = @"我的工作社交平台";
    desLabel.textColor = [UIColor colorWithHexString:@"#777777"];
    desLabel.font = [UIFont systemFontOfSize:14];
    desLabel.textAlignment = NSTextAlignmentLeft;
    [_iconView addSubview:desLabel];
}

- (void)setLoginView
{
    _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, _iconView.bottom + 45., kScreenWidth, 200.)];
    //_coverView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_coverView];
    
    ICLoginTextField *accField = [[ICLoginTextField alloc] initWithFrame:CGRectMake(LoginGap, 0, kScreenWidth-LoginGap*2, LoginFieldHeight) placeholder:@"员工账号"];
    accField.font = [UIFont systemFontOfSize:22];
    [_coverView addSubview:accField];
    [accField becomeFirstResponder];
    _accField = accField;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(accField.left, accField.bottom, accField.width, 0.5)];
    lineView.backgroundColor = ICRGB(0xd9d9d9);
    [_coverView addSubview:lineView];
    
    
    ICLoginTextField *passField = [[ICLoginTextField alloc] initWithFrame:CGRectMake(accField.left, lineView.bottom, accField.width, accField.height) placeholder:@"密码"];
    passField.font = [UIFont systemFontOfSize:22];
    passField.secureTextEntry = YES;
    [_coverView addSubview:passField];
    _passField = passField;
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(passField.left, passField.bottom, passField.width, 0.5)];
    lineView2.backgroundColor = ICRGB(0xd9d9d9);
    [_coverView addSubview:lineView2];
    
    
    UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(LoginGap, lineView2.bottom+20., lineView2.width, 40.)];
    [loginBtn setTitle:@"登录iCome" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [loginBtn.layer setMasksToBounds:YES];
    loginBtn.layer.cornerRadius = 5.0;
    [loginBtn setTitleColor:ICRGB(0xa9a9a9) forState:UIControlStateDisabled];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateDisabled];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:NE_BACKGROUND_COLOR] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [_coverView addSubview:loginBtn];
    _loginBtn = loginBtn;
    loginBtn.enabled = NO;
    
    
    UIButton *forgetBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-LoginGap-60., loginBtn.bottom+15., 70., 14+2)];
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    forgetBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [forgetBtn setTitleColor:ICRGB(0xa9a9a9) forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(forgetPassworClicked) forControlEvents:UIControlEventTouchUpInside];
    [_coverView addSubview:forgetBtn];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged) name:UITextFieldTextDidChangeNotification object:accField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged) name:UITextFieldTextDidChangeNotification object:passField];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - ICLoginProtocol

- (void)loginClicked:(NSString *)name
            passward:(NSString *)passward
{
    // 接口调用
    [MBProgressHUD showMessage:@"正在加载..." toView:self.view];
    __weak typeof(self)weak_self = self;
    [[ICLoginNetworkManager sharedInstance] loginLicensor:name password:passward success:^(NSDictionary *dic) {
        [MBProgressHUD hideHUDForView:weak_self.view];
        NSDictionary *data = [dic objectForKey:@"data"];
        NSString *token = [data objectForKey:@"token"];
        NSString *ticket = [data objectForKey:@"ticket"];
        NSDictionary *employee = [data objectForKey:@"employee"];
        
        
        [weak_self checkLoginStatusFromEmployee:employee];
        [[ICDatabaseManager shareManager] createMessageTables];
        

        if (![ICTools stringEmpty:token]) {   // 保存token
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"Token"];
            [[NSUserDefaults standardUserDefaults] setObject:ticket forKey:@"JSTicket"];
            NSString *userId = [NSString stringWithFormat:@"%@",[employee objectForKey:@"eId"]];
            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"user_Id"];
            [[NSUserDefaults standardUserDefaults] synchronize];
           
            [ICNetworkHelper setValue:[ICTools getToken] forHTTPHeaderField:@"token"];
            [ICNetworkHelper setValue:[ICTools getJSTicket] forHTTPHeaderField:@"auth"];

            [ICUser saveCurrentUserInfor:employee];
            [ICTools setDownLoadImageToken:token];
            
            UIViewController *viewController =[[IComMediator sharedInstance] IComMediator_MessageVController:nil];
            ICNavigationController *nav = [[ICNavigationController alloc] initWithRootViewController:viewController];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
            
            [[ICDefaultConfigManager sharedInstance] createDefaultGroups];
            [[ICDefaultConfigManager sharedInstance] initTCP];
        } else {    // 需要验证
            ICUser *user = [ICUser mj_objectWithKeyValues:employee];
            [ICUser saveCurrentUserInfor:employee];
            NSDictionary *dict = @{@"user":user,
                                   @"password":passward,
                                   @"name":name};
            UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_InformationConfirmController:dict];
            [self.navigationController pushViewController:viewController animated:YES];
        }
        
        NSDictionary * zoomNameP = @{@"password":passward,
                                     @"name":name};
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:zoomNameP forKey:@"zoomNameP"];
        [userDefaults synchronize];
        [[NSUserDefaults standardUserDefaults] setObject:passward forKey:@"mailPassword"];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:weak_self.view];
        [MBProgressHUD showError:error.domain];
    }];
}


-(void)deleteFileExist:(NSString *)fileName
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    if(result){
        [[ NSFileManager defaultManager ] removeItemAtPath:filePath error :NULL];
    }
}

// 新旧账号不同时：清除icom中旧用户数据
-(void)checkLoginStatusFromEmployee:(NSDictionary *)employee {
    NSString *oldUserId = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_Id"];
    NSString *newUserId = [NSString stringWithFormat:@"%@",[employee objectForKey:@"eId"]];
    if (![oldUserId isEqualToString:newUserId] && ![ICTools stringEmpty:oldUserId]) { // 新用户登录时 清除旧数据
        [ICTools clearAllLocateInfo];  // 清理用户聊天等本地存储信息
        //删除图片
        [self deleteFileExist:@"camera.png"];
        // 用户信息清理
        [ICUser releaseUser];
    } else {
        NSLog(@"is old user ");
    }
}

- (void)forgetPassworClicked
{
    //NSString *URLStr = @"http://come.enn.cn/EnnTIMPwdMgr/ResetPwdBySMS.jsp";
//    ICWebViewController *vc = [ICWebViewController jsBridgeWKWebViewWithPath:[ICJSBridgeTools appendUserInfoforJSURL:ResetPwdBySMS] title:@""];
//    vc.originalURL = ResetPwdBySMS;
//    [self.navigationController pushViewController:vc animated:YES];
    
//   UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_ResetPasswardViewController:nil];
//  [self.navigationController pushViewController:viewController animated:YES];
    
    [self pushCustomViewControllerURL:@"http://la.enn.cn:9080/EnnTIMPwdMgr/ResetPwdBySMS1.jsp" fromViewController:self animated:YES];

}

#pragma mark - private

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)login:(UIButton *)loginBtn
{
    [self loginClicked:_accField.text passward:_passField.text];
}

- (void)textFieldTextChanged
{
    self.loginBtn.enabled = (_passField.text.length>0 && _accField.text.length>0);
}

-(void)keyboardWillShow:(NSNotification *)note
{
    _iconView.centerX = kScreenWidth*0.78/2. + 5.;
    _iconView.centerY = iPhone5 ? (LoginIconViewTop+LoginIconViewHeight/2.-30):( LoginIconViewTop+LoginIconViewHeight/2.);
    __weak typeof(self)weak_self = self;
    [UIView animateWithDuration:1 animations:^{
        
        weak_self.iconView.transform = CGAffineTransformMakeScale(0.78, 0.78);
        weak_self.coverView.transform = CGAffineTransformMakeTranslation(0, iPhone5?-50:-30);
    }];
    
}

-(void)keyboardWillHide:(NSNotification *)note
{
    _iconView.centerX = kScreenWidth/2.;
    _iconView.centerY = LoginIconViewTop+LoginIconViewHeight/2.;
    __weak typeof(self)weak_self = self;
    [UIView animateWithDuration:1 animations:^{
        weak_self.iconView.transform = CGAffineTransformMakeScale(1, 1);
        weak_self.coverView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
